package dnl.toolbox.net;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class NetworkingUtils {

	/**
	 * Gets the first ip address that is not a loop-back address.
	 * 
	 * @return the first non loop-back address or <code>null</code> if non is
	 *         found.
	 */
	public static String getIpV4Address() {
		try {
			Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
			while (e.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) e.nextElement();
				Enumeration<InetAddress> e2 = ni.getInetAddresses();

				while (e2.hasMoreElements()) {
					InetAddress ip = (InetAddress) e2.nextElement();
					if (ip instanceof Inet4Address) {
						if (!"127.0.0.1".equals(ip.getHostAddress())) {
							return ip.getHostAddress();
						}
					}
				}
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
